package com.ruoyi.flow.service.flowable.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.flow.service.flowable.FlowableTaskService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.HistoryService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.api.history.HistoricTaskInstanceQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @title:
 * @author: bruce.liu
 * @since: 2024/10/23 14:54
 */
@Slf4j
@Service
@Transactional
public class FlowableTaskServiceImpl implements FlowableTaskService {
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;

    @Override
    public IPage<Task> runPage(IPage<Task> page, String userCode) {
        long firstResult = page.getCurrent() * page.getSize();
        IPage<Task> p = new Page<>();
        TaskQuery taskQuery = taskService.createTaskQuery();
        if (StringUtils.isNotEmpty(userCode)) {
            taskQuery.taskCandidateOrAssigned(userCode);
        }
        long count = taskQuery.count();
        p.setTotal(count);
        if (count > 0) {
            List<Task> tasks = taskQuery.listPage((int) firstResult, (int) page.getSize());
            p.setRecords(tasks);
        }
        return p;
    }

    @Override
    public IPage<HistoricTaskInstance> hisPage(IPage<Task> page, String userCode) {
        long firstResult = page.getCurrent() * page.getSize();
        IPage<HistoricTaskInstance> p = new Page<>();
        HistoricTaskInstanceQuery historicTaskInstanceQuery = historyService.createHistoricTaskInstanceQuery();
        if (StringUtils.isNotEmpty(userCode)) {
            historicTaskInstanceQuery.taskAssignee(userCode).or().taskCandidateUser(userCode);
        }
        long count = historicTaskInstanceQuery.count();
        p.setTotal(count);
        if (count > 0) {
            List<HistoricTaskInstance> tasks = historicTaskInstanceQuery.listPage((int) firstResult, (int) page.getSize());
            p.setRecords(tasks);
        }
        return p;
    }

    @Override
    public void complete(String taskId, Map<String, Object> variables) {
        taskService.complete(taskId, variables);
    }
}
